<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>语音识别</title>
</head>
<body>
    <h1>语音识别</h1>
    <button id="startRecording">开始录音</button>
    <button id="stopRecording" disabled>停止录音</button>
    <p id="status">等待录音...</p>
    <div id="result">识别结果将显示在这里。</div>

    <button id="summaryButton">总结</button>
    <div id="summaryResult">摘要结果将显示在这里。</div>

    <button id="startRecording_2">第二人开始录音</button>
    <button id="stopRecording_2" disabled>第二人停止录音</button>
    <p id="status_2">第二人等待录音...</p>
    <div id="result_2">第二人识别结果将显示在这里。</div>

    <button id="summaryButton_2">多人总结</button>
    <div id="summaryResult_2">多人摘要结果将显示在这里。</div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            let recorder;
            let audioChunks = [];
            let audioBlob;
            let transcriptions = []; // 存储转录结果的数组
            let transcriptions_2 = []; // 存储转录结果的数组
            let sequence = []; 

            const startRecordingButton = document.getElementById('startRecording');
            const stopRecordingButton = document.getElementById('stopRecording');
            const statusElement = document.getElementById('status');
            const resultElement = document.getElementById('result');
            const summaryButton = document.getElementById('summaryButton');
            const summaryResultElement = document.getElementById('summaryResult');

            const startRecordingButton_2 = document.getElementById('startRecording_2');
            const stopRecordingButton_2 = document.getElementById('stopRecording_2');
            const summaryButton_2 = document.getElementById('summaryButton_2');
            const summaryResultElement_2 = document.getElementById('summaryResult_2');
            const statusElement_2 = document.getElementById('status_2');
            const resultElement_2 = document.getElementById('result_2');

            startRecordingButton.addEventListener('click', startRecording);
            stopRecordingButton.addEventListener('click', stopRecording);
            summaryButton.addEventListener('click', summarizeTranscriptions);
            startRecordingButton_2.addEventListener('click', startRecording_2);
            stopRecordingButton_2.addEventListener('click', stopRecording_2);
            summaryButton_2.addEventListener('click', summarizeTranscriptions_2);

            function startRecording() {
                navigator.mediaDevices.getUserMedia({ audio: true })
                    .then((stream) => {
                        recorder = new MediaRecorder(stream);

                        recorder.ondataavailable = (e) => {
                            if (e.data.size > 0) {
                                audioChunks.push(e.data);
                            }
                        };

                        recorder.onstop = () => {
                            audioBlob = new Blob(audioChunks, { type: 'audio/m4a' });
                            const audioUrl = URL.createObjectURL(audioBlob);
                            resultElement.src = audioUrl;

                            // 保存音频Blob对象到本地存储（示例使用localStorage）
                            // localStorage.setItem('recordedAudio', JSON.stringify({
                            //     data: audioChunks.map(chunk => chunk.buffer),
                            //     type: 'audio/wav'
                            // }));

                            // 发送音频到后端进行处理
                            sendAudioToServer(audioBlob);
                            audioChunks = [];
                        };

                        recorder.start();
                        startRecordingButton.disabled = true;
                        stopRecordingButton.disabled = false;
                        startRecordingButton_2.disabled = true;
                        stopRecordingButton_2.disabled = true;
                        statusElement.textContent = '录音中...';
                    })
                    .catch((error) => {
                        console.error('getUserMedia error:', error);
                    });
            }

            function stopRecording() {
                recorder.stop();
                startRecordingButton.disabled = false;
                stopRecordingButton.disabled = true;
                startRecordingButton_2.disabled = false;
                stopRecordingButton_2.disabled = true;
                statusElement.textContent = '录音已停止，请等待结果...';
            }

            async function sendAudioToServer(audioBlob) {

                const apiUrl = 'http://127.0.0.1:5000/asr';  // 修改为你的后端接口地址
                const formData = new FormData();
                formData.append('audio', audioBlob, 'recording.m4a');

                // 显示 loading 状态
                resultElement.textContent = '正在识别，请稍候...';

                try {
                    const response = await fetch(apiUrl, {
                        method: 'POST',
                        body: formData
                    });
                    const data = await response.json();
                    console.log(data);
                    // 显示识别结果
                    resultElement.textContent = '识别结果: ' + data.transcription;
                    

                    // 在处理完成后进行赋值操作
                    resultElement.textContent = data.transcription
                    transcriptions.push(data.transcription);
                    sequence.push(0)
                } catch (error) {
                    console.error('Error sending audio to server:', error);
                    // 显示错误信息
                    // 添加延迟或停留几秒钟

                    resultElement.textContent = '识别出错，请稍后重试。';
                } finally {
                    // 后端处理完成后，可以在这里执行一些额外的逻辑
                    console.log('后端处理完成');
                    requestAnimationFrame(() => {});
                }
            }

            async function summarizeTranscriptions() {
                // 构建要发送给摘要接口的数据
                const requestData = {
                    transcriptions: transcriptions
                };

                // 发送请求到摘要接口
                try {
                    const summaryResponse = await fetch('http://127.0.0.1:5000/summary', {
                        method: 'POST',
                        body: JSON.stringify(requestData),
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });           
                    const summaryData = await summaryResponse.json();
                    console.log(summaryData);

                    // 在页面上显示摘要结果
                    summaryResultElement.textContent = '摘要结果: ' + summaryData.summary;
                } catch (error) {
                    console.error('Error summarizing transcriptions:', error);
                    // 显示错误信息
                    summaryResultElement.textContent = '总结出错，请稍后重试。';
                }
            }

            function startRecording_2() {
                navigator.mediaDevices.getUserMedia({ audio: true })
                    .then((stream) => {
                        recorder = new MediaRecorder(stream);

                        recorder.ondataavailable = (e) => {
                            if (e.data.size > 0) {
                                audioChunks.push(e.data);
                            }
                        };

                        recorder.onstop = () => {
                            audioBlob = new Blob(audioChunks, { type: 'audio/m4a' });
                            const audioUrl = URL.createObjectURL(audioBlob);
                            resultElement_2.src = audioUrl;

                            // 发送音频到后端进行处理
                            sendAudioToServer_2(audioBlob);
                            audioChunks = [];
                        };

                        recorder.start();
                        startRecordingButton_2.disabled = true;
                        stopRecordingButton_2.disabled = false;
                        startRecordingButton.disabled = true;
                        stopRecordingButton.disabled = true;
                        statusElement_2.textContent = '录音中...';
                    })
                    .catch((error) => {
                        console.error('getUserMedia error:', error);
                    });
            }

            function stopRecording_2() {
                recorder.stop();
                startRecordingButton_2.disabled = false;
                stopRecordingButton_2.disabled = true;
                startRecordingButton.disabled = false;
                stopRecordingButton.disabled = true;
                statusElement_2.textContent = '录音已停止，请等待结果...';
            }

            async function sendAudioToServer_2(audioBlob) {

                const apiUrl = 'http://127.0.0.1:5000/asr';  // 修改为你的后端接口地址
                const formData = new FormData();
                formData.append('audio', audioBlob, 'recording.m4a');

                // 显示 loading 状态
                resultElement_2.textContent = '正在识别，请稍候...';

                try {
                    const response = await fetch(apiUrl, {
                        method: 'POST',
                        body: formData
                    });
                    const data = await response.json();
                    console.log(data);
                    // 显示识别结果
                    resultElement_2.textContent = '识别结果: ' + data.transcription;
                    

                    // 在处理完成后进行赋值操作
                    resultElement_2.textContent = data.transcription
                    transcriptions_2.push(data.transcription);
                    sequence.push(1)
                } catch (error) {
                    console.error('Error sending audio to server:', error);
                    // 显示错误信息
                    // 添加延迟或停留几秒钟

                    resultElement_2.textContent = '识别出错，请稍后重试。';
                } finally {
                    // 后端处理完成后，可以在这里执行一些额外的逻辑
                    console.log('后端处理完成');
                    requestAnimationFrame(() => {});
                }
            }


            async function summarizeTranscriptions_2() {
                // 构建要发送给摘要接口的数据
                const requestData = {
                    transcriptions: transcriptions,
                    transcriptions_2: transcriptions_2,
                    sequence: sequence
                };

                // 发送请求到摘要接口
                try {
                    const summaryResponse = await fetch('http://127.0.0.1:5000/summary_2', {
                        method: 'POST',
                        body: JSON.stringify(requestData),
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });           
                    const summaryData = await summaryResponse.json();
                    console.log(summaryData);

                    // 在页面上显示摘要结果
                    summaryResultElement_2.textContent = '摘要结果: ' + summaryData.summary;
                } catch (error) {
                    console.error('Error summarizing transcriptions:', error);
                    // 显示错误信息
                    summaryResultElement_2.textContent = '总结出错，请稍后重试。';
                }
            }


        });
    </script>




</body>
</html>
